package com.zuper.demo.sessionlogin.config;

import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;

import com.zuper.demo.sessionlogin.constant.ErrorEnum;
import com.zuper.demo.sessionlogin.constant.SysConsts;
import com.zuper.demo.sessionlogin.exception.BusinessException;

public class MyLoginInterceptor implements HandlerInterceptor{
	@Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
		request.getServletContext().log(">> in MyLoginInterceptor preHandle");
		
		HttpSession session = request.getSession();
		request.getServletContext().log("sessionID: " + session.getId());
		
		Optional<Object> token = Optional.ofNullable(session.getAttribute(SysConsts.Session_Login_Key));
		if(token.isPresent()) { //not null
			request.getServletContext().log(">> 登录session未失效，继续正常流程！");
        } else {
        	request.getServletContext().log(ErrorEnum.Login_Session_Out.msg());
//        	Enumeration<String> enumHeader =  request.getHeaderNames();
//        	while(enumHeader.hasMoreElements()) {
//        		String name = enumHeader.nextElement();
//        		String value = request.getHeader(name);
//        		request.getServletContext().log("headerName: " + name + " headerValue: " + value);
//        	}
        	//尚未弄清楚为啥全局异常处理返回的响应中没有跨域需要的header，于是乎强行设置响应header达到目的 XD..
        	//希望有答案的伙伴可以不吝赐教
        	//@20190628 使用nginx代理转发实现跨域，不再需要后端跨域配置
//        	response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
//        	response.setHeader("Access-Control-Allow-Credentials", "true");
//        	response.setCharacterEncoding("UTF-8");
//            response.setContentType("text/html; charset=utf-8");
//            PrintWriter writer = response.getWriter();
//            writer.print(new BaseResult(ErrorEnum.Login_Session_Out));
//            return false;
        	throw new BusinessException(ErrorEnum.Login_Session_Out);
        }
		
        return true;
    }
}
